var categoriesCount = 0;

var TodoItems = function () {

    this.newItemTextAreaFocus = 0;

    var self = this;

    this.commands = []; // вводимые задания которые переключаются стрелками
    this.command_index; // индекс текущей команды

     var max_commands = 5; // всего храниться команд с учетом только что вводимой

    this.storage = new TodoStorage();

    this.storage.afterItemAdded = function () {
        self.render();
    }

    this.storage.afterSetItems = function () {
        self.render();
    }

    this.storage.onSyncError = function (data, textStatus, jqXHR) {
        if (textStatus != 'abort' && jqXHR != 'abort' && !(textStatus == 'error' && jqXHR == '')) {
            clearTimeout(this.syncTimer);

            /*
             var getTime = function(time, count) {
             if(count > 0) {
             return getTime(time * 2, count - 1);
             } else {
             return time;
             }
             };

             var time = getTime(5, self.storage.syncErrorsCount - 1 );

             self.showSyncMsg(time > 60 ? 60 : time, function () {
             self.storage.sync();
             });
             */

            var time = 5;

            time = time * self.storage.syncErrorsCount;

            self.showSyncMsg(time > 30 ? 30 : time, function () {
                self.storage.sync();
            });
        }
    }

    this.storage.onSyncSuccessful = function () {
        clearTimeout(self.syncMsgTimer);
        $('#message').fadeOut(400, function () {
            $(this).empty();
        });
    }

    this.config = {
        itemsContainer: '.list.default',
        template: _.template($('#item-template').html())
    };



    /* COMMANDS START*/
    /*
       АЛГОРИТМ РАБОТЫ

       команды заполнеяются в массив начиная с индекса max_commands и до 0, т е 5,4,3,2,1,0
       под индексом max_commands всегда находиться только что вводимая задача
       после подтвердения ввода клавишей Enter все записи сдвигаются влево
    */
    this.initCommand = function() {
        this.command_index = max_commands;
        for (i = 0; i <= max_commands; i++)
            this.commands[i] = '';
    }

    //ищем индекс следующей команды корторая не пустая если она существует
    this.findNextCommand = function() {
        for (i = 0; i <= max_commands; i++) {
            this.command_index++;
            if (this.command_index > max_commands)
                    this.command_index = 0;
            if (this.commands[this.command_index] != '') {
                return;
            }
        }
    }

    this.findPrevCommand = function() {
        
        
        for (i = 0; i <= max_commands; i++) {
            this.command_index--;
            if (this.command_index < 0)
                    this.command_index = max_commands;
            if (this.commands[this.command_index] != '') {
                return;
            }
        }
        
    }

    this.noLastCommand = function() {
        if (this.command_index == max_commands && this.commands[max_commands] == '')
            return true;
        return false;
    }

    this.shiftLeft = function() {
        for (i = 0; i < max_commands; i++) {
            this.commands[i] = this.commands[i+1];
        }
        this.commands[max_commands] = '';
        this.command_index = max_commands;

    }

    this.getCurrentCommand = function() {
        return this.commands[this.command_index];
    }

    this.saveEnteredCommand = function(a) {
        if (this.command_index == max_commands && a != '')
            this.commands[max_commands] = a;
    }

    this.saveCommands = function(a) {
        
        this.shiftLeft();
        if (!this.storage.findInStorage(a))
            this.commands[max_commands] = a;


    }


    /* COMMANDS END  */

    /**
     *
     */
    this.render = function () {
        //alert('in render');
        var items = this.storage.items;
        var categories = this.storage.categories;
        //alert(categories);

        if (typeof items != "object" || !items || !items.length) {
            return;
        }

        $(this.config.itemsContainer).html(this.config.template({ items: items, categories: categories }));

        this.afterRender();
    }

    /**
     *
     */
    this.afterRender = function () {
          //alert(categoriesCount);
        this.initDragAndDrop();
    }

    /**
     *
     */
    this.bindEvents = function () {
        var self = this;
		
		/**
         * Focus
        
		 
		$(document).on('keydown', 'body', function (e) {
            if (e.keyCode == 9) {
                $('#newitem textarea').focus();
            }
        }); */
        /* COMMANDS START*/
        $(document).on('focus', '#newitem textarea', function(e) {
               self.newItemTextAreaFocus = 1;

        });
   
        

        $(document).on('keyup', '#newitem textarea', function (e) {
            
             var value = $(this).val();
             
             self.saveEnteredCommand(value); // команда сохраниться только при правельном индексе
        });


        /* COMMANDS END*/
     


        /**
         * Add new item
         */
        $(document).on('keydown', '#newitem textarea', function (e) {
            if (e.keyCode == 13) { // ENTER
                // c3 start
                var value = $(this).val();

                if (value.indexOf('@') === 0)
                    self.storage.addCategory(value.replace(/(<([^>]+)>)/ig, ""));
                else
                    self.storage.addItem(value.replace(/(<([^>]+)>)/ig, ""));

                // c3 end
               // self.storage.addItem($(this).val().replace(/(<([^>]+)>)/ig, ""));
                $(this).val('').blur();
                self.newItemTextAreaFocus = 0;
                self.saveCommands(value);
            }

            if (e.keyCode == 27) { // ESC
                $(this).val('').blur();
                this.newItemTextAreaFocus = 0;
            }

            if (e.keyCode == 38 ) { // UP ARROW
                self.findPrevCommand();
                $(this).val(self.getCurrentCommand());
                
            }

            if (e.keyCode == 40 ) { // DOWN ARROW
                self.findNextCommand();
                $(this).val(self.getCurrentCommand());
               
            }
        });

        /**
         * Start editing
         */
        $(document).on('dblclick', '.items span', function () {

            $('#return').html($(this).parents('li').find('textarea').val().replace(/(<([^>]+)>)/ig, ""));

            var parent = $(this).parent('li');

            $(parent).addClass('editing');
            //$(this).replaceWith('<textarea class="edit" rows="1">' + $(this).text().replace(/(<([^>]+)>)/ig, "") + '</textarea>').find('textarea');

            $('textarea', parent).focus().select();
        });
        /**
         * Start editing category
         */
        $(document).on('dblclick', '.title span', function () {

            $('#return').html($(this).parent('li.title').find('textarea').val().replace(/(<([^>]+)>)/ig, ""));

            var parent = $(this).parent('li.title');

            $(parent).addClass('editing');
            //$(this).replaceWith('<textarea class="edit" rows="1">' + $(this).text().replace(/(<([^>]+)>)/ig, "") + '</textarea>').find('textarea');

            EnableSync = 0;

            $(parent).find('textarea:visible').focus().select();

        });

        /**
         * Textarea Resize
         */
        $(document).on('keydown keyup focus', '#name, .list textarea', function () {
            $('#clone').html($(this).val().replace(/(<([^>]+)>)/ig, ""));
            $(this).css('width', $('#clone').width() + 30);
            $(this).css('height', $('#clone').height());

            // Hide Mic

        });
        $(document).on('keydown keyup', '#name, .list textarea', function () {
            if ($('#name').val() != '') {
                $('#mic').css('opacity', 0);
                $('.clear').show();
            } else {
                $('#mic').css('opacity', 1);
                $('.clear').hide();
            }
        });

        $(document).on('webkitspeechchange', '#mic', function (e) {
            var result = $(this).val();
            $(this).val('');

            $('#name').val(result).focus();

            $(this).css('opacity', 0);
            $('.clear').show();
        });

        /**
         * Clear Textarea
         */
        $(document).on('click', '.clear', function () {
            $(this).hide();
            $('#mic').val('').css('opacity', 1);
            $('#newitem textarea').val('').focus();
        });

        /**
         * Item Check
         */
        $(document).on('click', 'label', function () {
            var itemId = $(this).parents('li').attr('data-internal-id');

            self.storage.updateItem(itemId, 'complete');
        });

        // Cancel Editing
        function itemEdit() {
            var element = '.items textarea:visible';
            var itemId = $(element).parents('li').attr('data-internal-id');

            if (itemId) {
                if ($(element).val() == '') {
                    self.storage.updateItem(itemId, 'delete');
                } else if($(element).val().replace(/(<([^>]+)>)/ig, "") != $('#return').html()){
                    self.storage.updateItem(itemId, 'edit', $(element).val().replace(/(<([^>]+)>)/ig, ""));
                } else {
                    $(element).parents('li').removeClass('editing');
                }
            }
        }

        function categoryEdit() {
            var element = '.title textarea:visible';
            var itemId = $(element).parents('li').attr('data-iternal-id');

            if (itemId) {
                if ($(element).val() == '') {
                    self.storage.updateCategory(itemId, 'delete');
                } else if($(element).val().replace(/(<([^>]+)>)/ig, "") != $('#return').html()){
                    self.storage.updateCategory(itemId, 'edit', $(element).val().replace(/(<([^>]+)>)/ig, ""));
                } else {
                    $(element).parents('li').removeClass('editing');
                }
            }
        }

        var onReturn = 0;

        $(document).on({
            'keydown': function (e) {

                if (e.keyCode == 13) {
                    onReturn = 1;

                    itemEdit();
                    categoryEdit();

                    EnableSync = 1;
                }

                if (e.keyCode == 27) {

                    $(this).parents('li').removeClass('editing');
                    EnableSync = 1;
                }
            },
            'blur': function () {

                if (onReturn == 0) {

                    itemEdit();
                    categoryEdit();
                } else {
                    onReturn = 0;
                }
            }
        }, '.list textarea:visible');

        $(document).on('click', '#message .content .resync-link', function (e) {
            e.preventDefault();
            self.syncStorage();
        })
    }

    this.init = function () {
        self.initCommand();

        self.bindEvents();


        self.storage.setItems(getFromStorage());
        self.storage.setCategories(getCategoriesFromStorage());
        //alert(self.storage.categories);
    };

    this.syncMsgTimer = null;

    this.showSyncMsg = function (time, callback) {
        var self = this;

        time = parseInt(time);

        clearTimeout(self.syncMsgTimer);

        var template = _.template($('#message-error-sync').html());
        $('#message').html(template({timeLeft: time}));
        if ($('#message').is(':hidden')) {
            $('#message').fadeIn(450);
        }

        if (time > 0) {
            self.syncMsgTimer = setTimeout(function () {
                self.showSyncMsg(time - 1, callback);
            }, 1000);
        } else if (typeof callback == "function") {
            callback();
        }
    }

    this.syncStorage = function () {
        var self = this;

        self.showSyncMsg(0, function () {
            self.storage.sync();
        });
    }


    this.initDragAndDrop = function () {

        var elements = '#dd0';
        for (i = 1; i <= categoriesCount; i++) {
            elements += ',#dd' + i;
        }
        $( elements ).sortable({
            items: "li:not(.date),li:not(.due),lu:not(.has-deadline)"
            ,connectWith: ".items"
            , stop:this.reorginizeDataAfterSort}).disableSelection();

        $('.list').sortable({items: "li:not(.ui-drag-disabled), li:not(.date)", stop:this.reorginizeDataAfterSort}).disableSelection();

        // alert(elements);

    }

    this.reorginizeDataAfterSort = function (evt, ui) {
        /*EnableSync = 0;

        var items = [];
        var categories = [];

        // parse items for default category
        $('li.ui-drag-disabled ul.items li').each(function(index, value) {
            id = $(this).attr('data-item-id');
            name = $(this).find('textarea').val();

            items.push({
                id: id,
                name: name,
                completed: false,
                deleted: false,
                category:'default',
                category_id:0,
                zindex:index

            });

        });
        // parse categories
        $('li.title').each(function(ind,val){
            category_id = $(this).attr('data-item-id');
            name = $(this).find('textarea').val();
            categories.push({
                id: category_id,
                name: name,
                zindex:ind,
                deleted: false
            });
            // in each category parse items

            $(this).find('ul.items li').each(function(i,v){
                classname = $(this).attr('class');
                if (classname != 'placeholder') {

                item_id = $(this).attr('data-item-id');
                name = $(this).find('textarea').val();

                    items.push({
                        id: item_id,
                        name: name,
                        completed: false,
                        deleted: false,
                        category:'default',
                        category_id:category_id,
                        zindex:i

                    });
                }
            });

        });

        self.storage.setItems(items);
        self.storage.setCategories(categories);

        EnableSync = 1;

        self.storage.sync();
        /*report = ''; // test code for debugging

         _.each(items, function(val,ind){

         if (val.category_id == 0)

         report += val.name + '=' + val.category_id + "\n";
         });

         _.each(categories, function(val,ind){
         report += val.name + '(cat)' + val.id + "\n";
         _.each(items, function(v,i){
         if (val.id == v.category_id)
         report += "\t" + v.name + '=' + v.zindex + "\n";

         });
         });

         alert(report);*/




    }

    this.init();
};

// Speech Input Fields
function transcribe(words) {

}

// c3 start
function isCategory(name) {

    if (name.indexOf('@') === 0)
         return true;
}

function existItemInCategory(category_id, items) {
    _.each(items, function (i, k) {
        alert(i);
        if (i.category_id == category_id)
          return true;
    });

    return false;
}




// c3 end